const express = require('express')
const body_parse = require('body-parser')
const cors = require('cors')
const session = require('express-session')
const app = express()
const port = 9002
const mysql = require('mysql');
const wechatRouter = require('./routes/wechat')
const managementRouter = require('./routes/management')
app.use(cors())
// 解析 post的payload
app.use(body_parse.urlencoded({ extended: false }))
app.use(body_parse.json())
// 后台session 
app.use(session({
    secret: "MMDCCJ****", // 密钥种子
    resave: false,
    saveUninitialized: true,
    cookie: {
        secure: false,
        maxAge: 3600 * 6 * 1000,
        httpOnly: false
    },
    name: 'status'
}))
// 连接数据库
const db = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: '020522',
    database: 'webserver'
});

// 管理界面的网页
app.use('/admin', express.static('./web'))
app.use('/', express.static('./dist'))
db.connect();
// 防止太久不访问导致数据库中断
const reflash = setInterval(function () {
    db.query('SELECT 1');
}, 1080000);


// 服务器启动网页
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
app.post('/api/add', (req, res) => {
    const body = req.body;
    if (!(body.name && body.text && body.date)) {
        return res.send("缺少参数")
    }
    const data = { name: body.name, date: body.date, text: body.text }
    const sqlstr = "INSERT INTO web SET ?";
    db.query(sqlstr, data, (err, result) => {
        if (err) return console.log(err);
        if (result.affectedRows === 1) {
            console.log("插入成功");
            res.send('200');
        }
    })
})
app.get('/api/get', (req, res) => {
    const sqlstr = "SELECT * FROM web ORDER BY DATE DESC LIMIT 11";
    db.query(sqlstr, (err, result) => {
        if (result.length == 0) {
            return res.send('400 查询失败')
        }
        return res.send({
            data: result
        })
    })
})
// VXAPP
app.use(wechatRouter)
app.use(managementRouter)


//VXAPP 后台管理 API
// 后台注册
